#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/un.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

#define UNIX_FILE  "/home/linux/CProject/network/UNIX/unixfile"
#define BACKLOG 5

int main(int args, const char * argv[]){

	int sockfd, newSockfd;
	int ret;
	struct sockaddr_un addr;
	// BUFSIZ 8192
	char buf[BUFSIZ] = {0};  
	//1. 创建套接字：IPV4、本地通信
	sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
	if(sockfd < 0){
		perror("socket");
		exit(0);
	}


	//2. 绑定通信结构体
	addr.sun_family = AF_UNIX;
	//定义本地文件
	strncpy(addr.sun_path, UNIX_FILE, sizeof(addr.sun_path)-1);
	
	if(bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1){
		perror("bind");
		exit(0);
	}

	//3. 监听套接字
	if(listen(sockfd, BACKLOG) == -1){
		perror("listen");
		exit(0);
	}

	//4. 处理客户端发起的连接，生成新的套接字
	newSockfd = accept(sockfd, NULL, NULL);
	if(newSockfd < 0){
		perror("accept");
		exit(0);
	}

	//5. 读取客户端上送的请求数据
	while(1){
		memset(buf, 0, BUFSIZ);
		ret = read(newSockfd, buf, BUFSIZ);
		if(ret == 0){
			//当把客户端关闭时，返回的就是0,此时一直打印No data,
			//所以后面加上break 退出循环
			printf("No data\n");
			break;
		}else if(ret < 0){
			//出错
			break;
		}else {
			printf("buf : %s", buf);
		}
	}

	//6. 关闭套接字以及删除本地通信文件
	close(sockfd);
	close(newSockfd);
	remove(UNIX_FILE);
	return 0;
}
